package com.k2data.k2app.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.k2data.k2app.common.OrikaMapperFactory;
import com.k2data.k2app.domain.DictDTO;
import com.k2data.k2app.domain.SysDict;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.SysDictMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lidong 17-3-6.
 */
@Log4j2
@Service
public class SysDictService {

    @Value("${web.gateway.url}")
    private String gatewayUrl;

    private final ConcurrentHashMap<String, List<SysDict>> dictCache = new ConcurrentHashMap<>();    // TODO redis

    private final SysDictMapper sysDictMapper;

    @Autowired
    public SysDictService(SysDictMapper testMapper) {
        this.sysDictMapper = testMapper;
    }

    @Transactional
    public long insert(SysDict sysDict) throws K2ResponseException {
        sysDictMapper.insertSelective(sysDict);
        return sysDict.getId();
    }

    @Transactional
    public int update(SysDict sysDict) throws K2ResponseException {
        int num = sysDictMapper.updateByPrimaryKeySelective(sysDict);
        return num;
    }

    public void refreshCache() {
        List<SysDict> list = sysDictMapper.selectAll();
        dictCache.clear();
        for (SysDict dictPO : list) {
            List<SysDict> innerList = dictCache.getOrDefault(dictPO.getType(), Lists.newArrayList());
            innerList.add(dictPO);
            dictCache.put(dictPO.getType(), innerList);
        }
    }

    public List<SysDict> getDictList(String type) {
//        if (dictCache.isEmpty()) { // TODO
        refreshCache();
//        }
        return dictCache.get(type);
    }

    /**
     * 根据类型获得字典 map, key 为 label 值
     *
     * @param type 类型
     * @return map
     */
    public Map<String, SysDict> getDictMap(String type) {
        List<SysDict> dictList = getDictList(type);

        return Maps.uniqueIndex(dictList, SysDict::getLabel);
    }


    public List<DictDTO> getList(String type,String typeCn,String label,String value) {
        SysDict dictPO = new SysDict();
        dictPO.setType(type);
        dictPO.setTypeCn(typeCn);
        dictPO.setLabel(label);
        dictPO.setValue(value);

        List<DictDTO> list = Lists.newArrayList();

        for (SysDict po : sysDictMapper.selectList(dictPO)) {
            DictDTO dto = OrikaMapperFactory.getMapper().map(po, DictDTO.class);

            if (po.getExt() != null) {
                dto.setExtTrans(Maps.newHashMap());
                for (Map.Entry<String, String> stringStringEntry : po.getExt().entrySet()) {
                    dto.getExtTrans().put(stringStringEntry.getKey(), stringStringEntry.getValue());
                }
            }

            if (dto.getExtTrans() != null && dto.getExtTrans().get("image") != null) {
                if ("industry".equals(dto.getType())) {
                    String filename = dto.getExtTrans().get("image");
                    String[] names = filename.split("\\.");
                    if (names.length == 2) {
                        dto.getExtTrans().put("image", gatewayUrl + Paths.get("/static/", names[0] + "-white." + names[1]));
                    } else {
                        dto.getExtTrans().put("image", gatewayUrl + Paths.get("/static/", filename));
                    }
                } else {
                    dto.getExtTrans().put("image", gatewayUrl + Paths.get("/static/", dto.getExt().get("image")));
                }
            }

            list.add(dto);
        }

        return list;
    }

}
